package org.liyufeng.project.addresslist;

import java.io.UnsupportedEncodingException;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.liyufeng.project.util.ParamesAPI;
import org.liyufeng.project.util.CommonUtil;
import org.liyufeng.project.pojo.Token;
import org.liyufeng.project.pojo.WeixinDepartment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * 通讯录部门管理类
 * @author liyufeng
 * @date   20141031
 **/
public class DepartmentManagement {
	private static Logger log = LoggerFactory.getLogger(DepartmentManagement.class);
	// 创建部门地址
	public static String CREATE_URL = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=ACCESS_TOKEN";
	// 更新部门地址
	public static String UPDATE_URL = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=ACCESS_TOKEN";
	// 删除部门地址
	public static String DELETE_URL = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=ACCESS_TOKEN&id=DEPTID";
	// 获取部门列表地址
	public static String GETLIST_URL = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=ACCESS_TOKEN";
	
	/**
	 * 创建部门
	 * @param accesstoken 
	 * @param name 部门名称。长度限制为1~64个字符
	 * @param parentid 父亲部门id。根部门id为1
	 * */
	public static int Create(String accesstoken , String name , String parentid){
		int errCode=0;
		String companyNmae ="";
		//拼接请求地址
		String requestUrl=CREATE_URL.replace("ACCESS_TOKEN", accesstoken);
		//需要提交的数据
		String postJson = "{\"name\":\"%s\",\"parentid\": %s}";
		
		try {
			
			companyNmae=new String(name.getBytes("ISO-8859-1"),"UTF-8"); 
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   
		
		String outputStr=String.format(postJson,companyNmae,parentid);
		//创建部门
		JSONObject jsonObject=CommonUtil.httpsRequest(requestUrl, "POST", outputStr);
		
		if(null!=jsonObject){
			if(0==jsonObject.getInt("errcode")){
				log.info("创建部门成功");
			}else{
				errCode=jsonObject.getInt("errcode");
				String errMsg=jsonObject.getString("errmsg");
				log.error("创建部门失败  errorcode:{} errmsg:{}",errCode,errMsg);
			}
		}
		return errCode;
	}
	
	/**
	 * 更新部门
	 * @param accesstoken 
	 * @param name 部门名称,长度限制为1~64个字符
	 * @param id   部门id
	 * */
	public static int Update(String accesstoken , String id , String name){
		int errCode=0;
		//拼接请求地址
		String requestUrl=UPDATE_URL.replace("ACCESS_TOKEN", accesstoken);
		//需要提交的数据
		String postJson = "{\"id\":\" %s\",\"name\":\"%s\"}";
		String outputStr=String.format(postJson, id, name);
		//创建部门
		JSONObject jsonObject=CommonUtil.httpsRequest(requestUrl, "POST", outputStr);
		
		if(null!=jsonObject){
			if(0==jsonObject.getInt("errcode")){
				log.info("更新部门成功");
			}else{
				errCode=jsonObject.getInt("errcode");
				String errMsg=jsonObject.getString("errmsg");
				log.error("更新部门失败  errorcode:{} errmsg:{}",errCode,errMsg);
			}
		}
		return errCode;
	}
	/**
	 * 删除部门
	 * @param accesstoken 
	 * @param id 部门id
	 * */
	public static int Delete(String accesstoken , String id){
		int errCode=0;
		//拼接请求地址
		String requestUrl=DELETE_URL.replace("ACCESS_TOKEN", accesstoken).replace("DEPTID", id);
		//删除部门
		JSONObject jsonObject=CommonUtil.httpsRequest(requestUrl, "GET", null);
		
		if(null!=jsonObject){
			if(0==jsonObject.getInt("errcode")){
				log.info("删除部门成功");	
			}else{
				errCode=jsonObject.getInt("errcode");
				String errMsg=jsonObject.getString("errmsg");
				log.error("删除部门失败  errorcode:{} errmsg:{}",errCode,errMsg);
			}
		}
		return errCode;
	}
	/**
	 * 获取部门列表
	 * @param accesstoken 
	 * */
	@SuppressWarnings({"unchecked","deprecation"})
	public static List<WeixinDepartment> GetList(String accesstoken){
		List<WeixinDepartment> weixinDepartment=null;
		//拼接请求地址
		String requestUrl=GETLIST_URL.replace("ACCESS_TOKEN", accesstoken);
		//获取部门列表
		JSONObject jsonObject=CommonUtil.httpsRequest(requestUrl, "GET", null);	
		if(null!=jsonObject){
			if(0==jsonObject.getInt("errcode")){
				log.info("获取部门列表成功");
				weixinDepartment=JSONArray.toList
						(jsonObject.getJSONArray("department"),WeixinDepartment.class);
			}else{
				weixinDepartment=null;
				int errCode=jsonObject.getInt("errcode");
				String errMsg=jsonObject.getString("errmsg");
				log.error("获取部门列表失败  errorcode:{} errmsg:{}",errCode,errMsg);	
			}
		}
		return weixinDepartment;
	}
	@SuppressWarnings({"unchecked","deprecation"})
	public static List<WeixinDepartment> GetListByID(String accessToken, String id) {
		List<WeixinDepartment> weixinDepartment=null;
		//拼接请求地址
		String requestUrl=GETLIST_URL.replace("ACCESS_TOKEN", accessToken).replace("ID", id);
		String postJson = "{\"id\":\" %s\"}";
		String outputStr=String.format(postJson, id);
		
		//获取部门列表
		JSONObject jsonObject=CommonUtil.httpsRequest(requestUrl, "GET", outputStr);	
		if(null!=jsonObject){
			if(0==jsonObject.getInt("errcode")){
				log.info("获取部门列表成功");
				weixinDepartment=JSONArray.toList
						(jsonObject.getJSONArray("department"),WeixinDepartment.class);
			}else{
				weixinDepartment=null;
				int errCode=jsonObject.getInt("errcode");
				String errMsg=jsonObject.getString("errmsg");
				log.error("获取部门列表失败  errorcode:{} errmsg:{}",errCode,errMsg);	
			}
		}
		return weixinDepartment;
	}
	//示例
	public static void main(String[] args) {
		// 调用接口获取凭证
		Token token = CommonUtil.getToken(ParamesAPI.corpId, ParamesAPI.corpsecret);
		if (null != token) {
			// 创建部门
//			int errCode=Create(token.getAccessToken(),"test1" ,"1");
			int errCode=Update(token.getAccessToken(),"3" ,"中心");
			//int errCode=Delete(token.getAccessToken(),"2");
			
			List<WeixinDepartment> departmentList=GetList(token.getAccessToken());
			
//			if(0==errCode){
//				System.out.println("操作成功");
//			}
//			else {
//				System.out.println("操作失败");
//			}
			for(WeixinDepartment department:departmentList){
				System.out.println(String.format("ID: %d Name: %s ParentId: %d", department.getId(),department.getName(),department.getParentid()));
			}
			
		}
	}

	
}
